package com.ruoyi.tzai.config;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 任务执行器线程池配置
 * 
 * @author tzai
 * @date 2025-11-12
 */
@Configuration
@EnableAsync
public class TaskExecutorConfig 
{
    @Value("${tzai.task.executor.core-pool-size:5}")
    private int corePoolSize;

    @Value("${tzai.task.executor.max-pool-size:10}")
    private int maxPoolSize;

    @Value("${tzai.task.executor.queue-capacity:50}")
    private int queueCapacity;

    @Value("${tzai.task.executor.keep-alive-seconds:60}")
    private int keepAliveSeconds;

    /**
     * 任务执行器线程池
     */
    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数
        executor.setCorePoolSize(corePoolSize);
        
        // 最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        
        // 队列容量
        executor.setQueueCapacity(queueCapacity);
        
        // 线程名称前缀
        executor.setThreadNamePrefix("task-executor-");
        
        // 拒绝策略：由调用线程处理
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 线程空闲时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        
        // 等待所有任务完成后关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        
        // 等待时间
        executor.setAwaitTerminationSeconds(60);
        
        executor.initialize();
        
        return executor;
    }
}

